package com.example.wyemail.util;

import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 软件启动工具类
 *
 * @author fxab
 * @date 2024/06/06
 */
public class SoftInitUtil {
    /**
     * 开始
     *
     * @param clientPath 客户端路径
     */
    public static void Start(String clientPath) {
        // 创建一个新线程来启动客户端程序
        Thread clientThread = new Thread(() -> {
            try {
                // 创建File对象表示客户端应用程序文件
                File clientFile = new File(clientPath);

                // 检查文件是否存在
                if (clientFile.exists()) {
                    // 获取桌面实例
                    Desktop desktop = Desktop.getDesktop();

                    // 启动客户端应用程序并将其放在桌面
                    desktop.open(clientFile);
                    System.out.println("客户端启动中...");
                } else {
                    System.out.println("客户端应用程序文件不存在：" + clientPath);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        clientThread.start();
    }

    public static void Stop(){
        try {
            String line;
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("windows")) {
                System.out.println("Running on Windows");

                // 使用Windows默认的字符编码（通常是GBK）
                ProcessBuilder builder = new ProcessBuilder("tasklist");
                Process process = builder.start();

                // 获取Windows命令行输出时，指定GBK编码
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));

                while ((line = reader.readLine()) != null) {
//                    System.out.println("Reading line: " + line); // 调试信息
                    if (line.contains("mailmaster")) {
                        String[] parts = line.split("\\s+");
                        // 避免数组越界和字符串拆分不正确的问题
                        if (parts.length > 1) {
                            String pid = parts[1];
                            System.out.println("Found process with PID: " + pid);
                            Runtime.getRuntime().exec("taskkill /F /PID " + pid);
                            System.out.println("Process killed: PID " + pid);
                        }
                    }
                }
                reader.close();
            } else {
                // Unix-like系统使用pkill命令
                System.out.println("Running on Unix-like system");
                Runtime.getRuntime().exec(new String[]{"pkill", "-f", "mailmaster"});
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
